//
//  HMPictureViewCell.swift
//  MicroBlog
//
//  Created by QT on 15/8/8.
//  Copyright © 2015年 綦敦涛. All rights reserved.
//

import UIKit
import SDWebImage

// 设置代理
protocol HMPictureCellDelegate: NSObjectProtocol{
    func pictureViewScale(scale: CGFloat)
}

class HMPictureViewCell: UICollectionViewCell {
    // 设置代理属性
    weak var pictureDelegate: HMPictureCellDelegate?
    
    var url: NSURL?{
        didSet{
            indicator.startAnimating()
            picView.image = nil
            resetScrollView()
            
            
            picView.sd_setImageWithURL(url) { (image, error, _, _) -> Void in
              

                
                // 模拟延迟
                // 模拟延时
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(1)), dispatch_get_main_queue(), {
                    //TODO: -模拟延迟
                    self.currentPic = image
                    
                    self.indicator.stopAnimating()
                    let size = self.setPicSize(image)
                    // 设置图片尺寸
                    self.picView.bounds = CGRect(origin: CGPointZero, size: size)
                    // 设置图片位置
                    self.setPicPos()
                })
                
//                self.currentPic = image
//                
//                self.indicator.stopAnimating()
//                let size = self.setPicSize(image)
//                // 设置图片尺寸
//               self.picView.bounds = CGRect(origin: CGPointZero, size: size)
//                // 设置图片位置
//                self.setPicPos()
            }
        }
    }
    // 复原scrollView
    func resetScrollView(){
        scrollView.contentInset = UIEdgeInsetsZero
        scrollView.contentOffset = CGPointZero
        scrollView.contentSize = CGSizeZero
        
    }
    
    var currentPic: UIImage?
    
    private func setPicSize(pic: UIImage) -> CGSize{
        let w = UIScreen.mainScreen().bounds.width
        let scale =  w / pic.size.width
        let h = pic.size.height * scale
        
        return CGSize(width: w, height: h)
    }
    
    private func setPicPos(){
        let s = setPicSize(picView.image!)
        
        if s.height > UIScreen.mainScreen().bounds.height{
            // 长图
            scrollView.contentSize = s
            picView.frame = CGRect(origin: CGPointZero, size: s)
        }else{
            // 宽图，处置居中
            let y = ( UIScreen.mainScreen().bounds.height - s.height ) * 0.5
//            picView.frame = CGRect(origin: CGPoint(x: 0, y: y), size: s)
            picView.frame = CGRect(origin: CGPointZero, size: s)
            scrollView.contentInset = UIEdgeInsets(top: y, left: 0, bottom: y, right: 0)
        }
    }
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
    setUI()
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setUI(){
        scrollView.addSubview(picView)
        contentView.addSubview(scrollView)
        // 设置scroll代理及缩放属性
        scrollView.delegate = self
        scrollView.minimumZoomScale = 0.5
        scrollView.maximumZoomScale = 2
        
        scrollView.translatesAutoresizingMaskIntoConstraints = false
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[sc]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["sc":scrollView]))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[sc]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["sc":scrollView]))
        
//        contentView.backgroundColor = UIColor.greenColor()
        contentView.addSubview(indicator)
        // 设置指示器约束
        indicator.translatesAutoresizingMaskIntoConstraints = false
        contentView.addConstraint(NSLayoutConstraint(item: indicator, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
        contentView.addConstraint(NSLayoutConstraint(item: indicator, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))
    }
    
    
    private lazy var scrollView = UIScrollView()
    private lazy var picView = UIImageView()
    private lazy var indicator = UIActivityIndicatorView()
}


extension HMPictureViewCell: UIScrollViewDelegate{
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        return picView
    }
    func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {
        // 重新计算位置
//        let size = picView.frame.size
        var x = ( UIScreen.mainScreen().bounds.width - picView.frame.width ) * 0.5
        x = (x < 0 ? 0 : x )
        var y = ( UIScreen.mainScreen().bounds.height - picView.frame.height) * 0.5
        y = (y < 0 ? 0 : y )
        scrollView.contentInset = UIEdgeInsets(top: y, left: x, bottom: y, right: x)
        
        
        let scale = picView.transform.a
        
        print(scale)
        
        pictureDelegate?.pictureViewScale(scale)
    }
}